import React, { useState } from 'react'
import { Form, Input, Button, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { userApi } from '../../api/user'
import { setUserInfo, setToken } from '../../store/slices/userSlice'
import './style.scss'

const Login = () => {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const dispatch = useDispatch()

  const onFinish = async (values) => {
    try {
      setLoading(true)
      const res = await userApi.login(values)
      dispatch(setUserInfo(res.userInfo))
      dispatch(setToken(res.token))
      message.success('登录成功')
      navigate('/home')
    } catch (error) {
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="login-container">
      <div className="login-box">
        <h2>网络攻击仿真系统</h2>
        <Form onFinish={onFinish}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item name="captcha" rules={[{ required: true, message: '请输入验证码' }]}>
            <div className="captcha-container">
              <Input placeholder="验证码" />
              <img src="/sys/getVerify" alt="验证码" onClick={(e) => e.target.src = '/sys/getVerify?' + Date.now()} />
            </div>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
